
var skuCreateTable;
var deleteflg=false;
var reg = /^[0-9a-zA-Z]+$/; //正则表达式 英文或者数字
var regNumCharHanzi = /^[0-9a-zA-Z\u4e00-\u9fa5]+$/; //正则表达式 中文或英文或者数字
var cashReg = /^[0-9]+(.[0-9]{0,2})?$/;//金额正则表达式
var arrDelGoodsSkuId = new Array(); //删除规格
var map = {};//记录原始的规格数据
/**
 * 页面初始化
 */
$(function () {
    $('#createSku').on('click', function () {
        skuCreateTable.fnAddData([
            '',
           '',
           '',
           '',
           '',
           '否',
           '否',
           '',
           '<a href="javascript:;" class="delete" goodsSkuId="">删除</a>'
        ])
        skuCreateTable.fnDraw();
    } );

//    $("#skuCreateTable").tooltip({
//        selector: ".tooltip-column-detail",
//        container: "body",
//        title: function() {
//            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
//                return $(this).text();
//            }
//        }
//    });
    //
    $('#skuCreateTable').on('click', 'td', function (e) {
        if (deleteflg==true){
            deleteflg=false;
            return;
        }
        deleteflg=false;
        //e.preventDefault();
        var nRow = $(this).parents('tr')[0];
        if (nEditing !== null && nEditing != nRow) {
            saveRow(skuCreateTable, nEditing);
            editRow(skuCreateTable, nRow);
            nEditing = nRow;
        } else {
            var text = $(this).parent().find("input");
            if (text.length<=0){
                editRow(skuCreateTable, nRow);
            }
            nEditing = nRow;
        }
    });
    function delGoodsSku(event){
        if (nEditing !== null && nEditing != event.data.nRow) {
            saveRow(skuCreateTable, nEditing);
        }
        if(event.data.goodsId == ""){
        	arrDelGoodsSkuId.push(event.data.goodsId);
            skuCreateTable.fnDeleteRow(event.data.nRow);
            nEditing = null;
            return;
        }
        $.ajax({
            type : "GET",
            url : "/goods/deleteGoods.action?skuId=" + event.data.goodsId,
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : true,// 同步
            success : function(data) {
                if (data.result == "success") {
//                    删除数据库存在的数据的时候，需要记录
                  arrDelGoodsSkuId.push(event.data.goodsId);
                  skuCreateTable.fnDeleteRow(event.data.nRow);
                  nEditing = null;
                  window.top.window.showScoMessage("ok", data.msg);
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });

    }
    
    $('#skuCreateTable').on('click', 'a.delete', function (e) {
        deleteflg = true;
        e.preventDefault();
        var nRow = $(this).parents('tr')[0];
        window.top.window.$("#modalConfirmContent").text("要删除该行吗?");
        window.top.window.$('#btnModalOK').unbind();
        window.top.window.$("#btnModalOK").on('click', '',{nRow:nRow,goodsId:$(this).attr("goodsskuid")}, delGoodsSku);
        window.top.window.$('#modal-confirm').modal({show:true, backdrop:'static'});
    });
    
    function editRow(oTable, nRow) {
        var aData = oTable.fnGetData(nRow);
        var temp = aData[8].split("goodsSkuId=");
        var goodsSkuId=temp[1].split(">",1);
        goodsSkuId = goodsSkuId.toString().replace(/\"/g,"");
        
        var rTds = $('>td', nRow);
        if (goodsSkuId===''){
            rTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[0] + '" readonly="readonly" placeholder="后台自动生成">';
            rTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[1] + '">';
        }
        rTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[2] + '">';
        rTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[3] + '">';
        rTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[4] + '">';
        if ("否" == aData[5]){
            rTds[5].innerHTML = '<input type="checkbox" /></input>';
        } else {
            rTds[5].innerHTML = '<input type="checkbox" checked="checked" /></input>';
        }
        if ("否" == aData[6]){
            rTds[6].innerHTML = '<input type="checkbox" /></input>';
        } else {
            rTds[6].innerHTML = '<input type="checkbox" checked="checked" /></input>';
        }    
        rTds[7].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[7] + '">';
    }

    function saveRow(oTable, nRow) {
        var rInputs = $('input', nRow);
        var aData = oTable.fnGetData(nRow);
        var temp = aData[8].split("goodsSkuId=");
        var goodsSkuId=temp[1].split(">",1);
        goodsSkuId = goodsSkuId.toString().replace(/\"/g,"");
        if ((goodsSkuId=='' && rInputs.length == 8) || (goodsSkuId!=='' && rInputs.length == 6)){
            if (rInputs.length == 8){
                oTable.fnUpdate(rInputs[0].value, nRow, 0, false);
                oTable.fnUpdate(rInputs[1].value, nRow, 1, false);
                oTable.fnUpdate(rInputs[2].value, nRow, 2, false);
                if (rInputs[3].value==""){
                    oTable.fnUpdate("0", nRow, 3, false);
                }else {
                    oTable.fnUpdate(rInputs[3].value, nRow, 3, false);    
                }                
                if (rInputs[4].value==""){
                    oTable.fnUpdate("0", nRow, 4, false);
                }else{
                    oTable.fnUpdate(rInputs[4].value, nRow, 4, false);
                }                
                if (rInputs[5].checked==true){
                    oTable.fnUpdate("是", nRow, 5, false);
                } else {
                    oTable.fnUpdate("否", nRow, 5, false);
                }
                if (rInputs[6].checked==true){
                    oTable.fnUpdate("是", nRow, 6, false);
                } else {
                    oTable.fnUpdate("否", nRow, 6, false);
                }
                oTable.fnUpdate(rInputs[7].value, nRow, 7, false);
            }else {
                oTable.fnUpdate(rInputs[0].value, nRow, 2, false);
                oTable.fnUpdate(rInputs[1].value, nRow, 3, false);
                oTable.fnUpdate(rInputs[2].value, nRow, 4, false);
                if (rInputs[3].checked==true){
                    oTable.fnUpdate("是", nRow, 5, false);
                } else {
                    oTable.fnUpdate("否", nRow, 5, false);
                }
                if (rInputs[4].checked==true){
                    oTable.fnUpdate("是", nRow, 6, false);
                } else {
                    oTable.fnUpdate("否", nRow, 6, false);
                }
                oTable.fnUpdate(rInputs[5].value, nRow,7, false);
            }
            
            oTable.fnDraw();
        }
    }

    function rollbackRow(oTable, nRow) {
        var aData = skuCreateTable.fnGetData(nRow);
        var rTds = $('>td', nRow);
        for (var i = 0, iLen = rTds.length; i < iLen; i++) {
            skuCreateTable.fnUpdate(aData[i], nRow, i, false);
        }
        skuCreateTable.fnDraw();
    }
    
 // 创建保存按钮点击事件绑定
    $("#btnGoodsAdd").click(function(){
        
        //系统商品信息，其中包括商品，规格集合
        var goodsInfo=new Object();
        //商品信息
        var goods = new Object();
        //规格集合
        var arrSku=new Array();
        var sku = new Object();
        var flg = true;
        if (!checkGoodItem()){
            return;
        }
        
        //整备商品表
        goods.goodCode = window.top.window.$("#goodCode").val();
        goods.goodName = window.top.window.$("#goodName").val();
        goods.catgId = window.top.window.$("#catgId").val();
        goods.catgName = window.top.window.$("#catgName").val();
        goods.remark = window.top.window.$("#remark").val();
        goods.action = "insert";
        
        // 增加保存数据时的是否开启序列号管理的开关
        if(window.top.window.$("#isSn").is(':checked')){
            goods.isSn = "y";
        }else{
            goods.isSn = "n";
        }
        
        goodsInfo.goods = goods;
        goodsInfo.action = "insert"
        //规格表值同步
        if (nEditing!=null){
            saveRow(skuCreateTable, nEditing);    
        }

        //规格表的数据取得
        window.top.window.$('#skuCreateTable tbody tr').each(function(){
            var sku = new Object();
            var aData = skuCreateTable.fnGetData(this);
            
            if ((aData[1] !== null && aData[1] !== undefined && $.trim(aData[1]) !== '')
                    || (aData[2] !== null && aData[2] !== undefined && $.trim(aData[2]) !== '')
                    || (aData[3] !== null && aData[3] !== undefined && $.trim(aData[3]) !== '')
                    || (aData[4] !== null && aData[4] !== undefined && $.trim(aData[4]) !== '')) {
                if (!checkGoodSku(aData)){
                    flg = false;
                    return;
                }
                sku.action = "insert";
//                sku.skuMCode = aData[0];后台自动生成
                sku.skuCode = aData[1];
                sku.skuName = aData[2];
                sku.stanPurcPrice = aData[3];
                sku.price = aData[4];
                sku.bar = aData[7];
                sku.gift = aData[5];
                sku.virt = aData[6];
                arrSku.push(sku);
            }
        });
        
        if (!flg){
            return;
        }
        
        goodsInfo.arrSku = arrSku;
//        alert(JSON.stringify(goodsInfo));
        window.top.window.returnCustomModalDialog();
        var loading = window.top.window.getIndexBusyOverlay();
     // 父窗体归还本页的编辑对话框
        //后台交互
        $.ajax({
            type:"POST",
            url:"/goods/updateGoods.action",
            data:JSON.stringify(goodsInfo),
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
//            async: false, // 同步
            success:function(data) {
            	loading.remove();
                if (data.success == "y") {
                   $('#modalCreate').modal('hide');
                   window.top.window.showScoMessage('ok', '添加成功');
                   goodsTable.draw();
                } else{
                    window.top.window.showModalAlert(data.errormessage);
                    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
                    editDialog.modal({show:true, backdrop:'static'});
                }
                
            },
            error:function(XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
            });
        
        
    });
    
 // 创建保存按钮点击事件绑定
    $("#btnGoodsUpdate").click(function(){
        //系统商品信息，其中包括商品，规格集合
        var goodsInfo=new Object();
        //商品信息
        var goods = new Object();
        //规格集合
        var arrSku=new Array();
        var sku = new Object();
        var flg = true;
        var skuCount = 0;
        var goodsCount = 0;
        if (!checkGoodItem()){
            return;
        }
        
        //整备商品表
        if (window.top.window.$("#goodCode").val()!==window.top.window.$("#goodCodehid").val() 
                || window.top.window.$("#goodName").val()!==window.top.window.$("#goodNamehid").val()
                || window.top.window.$("#goodType").val()!==window.top.window.$("#goodTypehid").val()
                || window.top.window.$("#remark").val()!==window.top.window.$("#remarkhid").val()){
            
            goods.action = "update";
            goodsCount = 1;
        } 
        goods.goodCode = window.top.window.$("#goodCode").val();
        goods.goodName = window.top.window.$("#goodName").val();
        goods.catgId = window.top.window.$("#catgId").val();
        goods.catgName = window.top.window.$("#catgName").val();
        goods.remark = window.top.window.$("#remark").val();
        goods.id = window.top.window.$("#goodsId").val();
        
        // 增加保存数据时的是否开启序列号管理的开关
        if(window.top.window.$("#isSn").is(':checked')){
            goods.isSn = "y";
        }else{
            goods.isSn = "n";
        }
        
        goodsInfo.goods = goods;
        goodsInfo.action = "update"
        //规格表值同步
        if (nEditing!=null){
            saveRow(skuCreateTable, nEditing);    
        }

        //规格表的数据取得
        window.top.window.$('#skuCreateTable tbody tr').each(function(){
            
            var sku = new Object();
            var aData = skuCreateTable.fnGetData(this);
            if (aData == null){
                return;
            }
            skuCount++;
            var temp = aData[8].split("goodsSkuId=");
            var goodsSkuId=temp[1].split(">",1);
            goodsSkuId = goodsSkuId.toString().replace(/\"/g,"");
            if ((aData[0] !== null && aData[0] !== undefined && $.trim(aData[0]) !== '') 
                    || (aData[1] !== null && aData[1] !== undefined && $.trim(aData[1]) !== '')
                    || (aData[2] !== null && aData[2] !== undefined && $.trim(aData[2]) !== '')) {
                if (!checkGoodSku(aData)){
                    flg = false;
                    return;
                }
                if (goodsSkuId==""){
                    sku.action = "insert";
                    sku.skuMCode = aData[0];
                    sku.skuCode = aData[1];
                    sku.skuName = aData[2];
                    sku.stanPurcPrice = aData[3];
                    sku.price = aData[4];
                    sku.bar = aData[7];
                    sku.gift = aData[5];
                    sku.virt = aData[6];
                    arrSku.push(sku);
                } else {
                    var skuValue = map[goodsSkuId];
                    var a4 = "n";
                    var a5 = "n";
                    if (aData[5]=="是"){
                        a4 = "y";
                    } 
                    if (aData[6]=="是"){
                        a5 = "y";
                    }
                    if (skuValue !== aData[0] + "," + aData[1]+","+aData[2]+","+aData[3]+","+aData[4]+","+a4+","+a5+","+aData[7]){
                        sku.action = "update";
                        sku.skuMCode = aData[0];
                        sku.skuCode = aData[1];
                        sku.skuName = aData[2];
                        sku.stanPurcPrice = aData[3];
                        sku.price = aData[4];
                        sku.bar = aData[7];
                        sku.gift = aData[5];
                        sku.virt = aData[6];
                        sku.id = goodsSkuId;
                        arrSku.push(sku);
                    }
                    delete map[goodsSkuId];
                }
                
            }
        });
        
        if (!flg){
            return;
        }
        if (skuCount==0){
            window.top.window.showModalAlert("规格至少有一条。");
            return;
        }
        
        $.each(map,function(key,values){  
            var sku = new Object(); 
            sku.action = "delete";
            sku.id = key;
            arrSku.push(sku);
          });  
        
        if (arrSku.length == 0 && goodsCount==0){
            window.top.window.showModalAlert("没有需要更新的数据。");
            return;
        }
        
        
        goodsInfo.arrSku = arrSku;
        window.top.window.returnCustomModalDialog();
     // 父窗体归还本页的编辑对话框
        //后台交互
        var loading = window.top.window.getIndexBusyOverlay();
        $.ajax({
            type:"POST",
            url:"/goods/updateGoods.action",
            data:JSON.stringify(goodsInfo),
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
//            async: true, // 同步
            success:function(data) {
            	loading.remove();
                if (data.success == "y") {
                   $('#modalCreate').modal('hide');
                   goodsTable.draw();
                } else{
                    window.top.window.showModalAlert(data.errormessage);
                    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
                    editDialog.modal({show:true, backdrop:'static'});
                }
                
            },
            error:function(XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
            });
        
        
    });
    
});

function checkGoodSku(aData){

    var skuCode = aData[1];
    if (skuCode == null || skuCode == undefined || $.trim(skuCode) == '') { 
        window.top.window.showModalAlert("规格商家编码为空");
        return false;
    }
    
    if (skuCode.length > 100){
        window.top.window.showModalAlert("规格商家编码超过100");
        return false;
    }
    
//    if(!regNumCharHanzi.test(skuCode)){
//        window.top.window.showModalAlert("规格商家编码请输入中文，英文或者数字");
//        return false;
//    }
    
    //规格名称
    var skuName = aData[2];
    if (skuName == null || skuName == undefined || $.trim(skuName) == '') { 
        window.top.window.showModalAlert("规格名称为空");
        return false;
    }
    
    if (skuName.length > 100){
        window.top.window.showModalAlert("规格名称超过100");
        return false;
    }
    
  //进价
    var stanPurcPrice = aData[3];
    if (stanPurcPrice == null || stanPurcPrice == undefined || $.trim(stanPurcPrice) == '') { 
        window.top.window.showModalAlert("标准进价为空");
        return false;
    }
    
    if (stanPurcPrice.length > 12){
        window.top.window.showModalAlert("标准进价超过12位输入");
        return false;
    }
    
    if(!cashReg.test(stanPurcPrice)){
        window.top.window.showModalAlert("标准进价非两位小数的正实数");
        return false;
    }
    
    //售价
    var price = aData[4];
    if (price == null || price == undefined || $.trim(price) == '') { 
        window.top.window.showModalAlert("标准售价为空");
        return false;
    }
    
    if (price.length > 12){
        window.top.window.showModalAlert("标准售价超过12位输入");
        return false;
    }
    
    if(!cashReg.test(price)){
        window.top.window.showModalAlert("标准售价非两位小数的正实数");
        return false;
    }
    
  //条码
    var barCode = aData[7];
    if(barCode.length > 0){
    	if (barCode.length > 25){
            window.top.window.showModalAlert("条码超过25");
            return false;
        }
        
        if(!reg.test(barCode)){
            window.top.window.showModalAlert("条码请输入英文或者数字");
            return false;
        }
    }
    
    
    return true;
    
}

function checkGoodItem(){
    
    //商品编码
    var goodCode = window.top.window.$("#goodCode").val();
    if (goodCode == null || goodCode == undefined || $.trim(goodCode) == '') { 
        window.top.window.showModalAlert("商品商家编码为空");
        return false;
    }
    
    if (goodCode.length > 100){
        window.top.window.showModalAlert("商品商家编码超过100");
        return false;
    }
    
//    if(!regNumCharHanzi.test(goodCode)){
//        window.top.window.showModalAlert("商品商家编码请输入中文，英文或者数字");
//        return false;
//    }
    
    //商品名称
    var goodName = window.top.window.$("#goodName").val();
    if (goodName == null || goodName == undefined || $.trim(goodName) == '') { 
        window.top.window.showModalAlert("商品名称为空");
        return false;
    }
    
    if (goodName.length > 100){
        window.top.window.showModalAlert("商品名称超过100");
        return false;
    }
    
    return true;
}

function initGoodsDiv(){
    $("#isSn").iCheck({
        checkboxClass : 'icheckbox_flat-red',
        radioClass : 'iradio_flat-red'
    });
    $('#skuCreateTable').dataTable().fnClearTable();
    //规格新规列表
      skuCreateTable = $('#skuCreateTable').dataTable({
          "bPaginate": false,
          "bAutoWidth": true,
          "bScrollAutoCss":false,
          "sScrollY" : '200px',
          "bSort" : false,
          "searching": false,
          "bDeferRender": true,
          "bDestroy": true,
          "dom": '<"bottom"rtflp>',
          "columnDefs" : [{
	        	"className" : "truncate-text",
	            "targets" : [ 0 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 1 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 2 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 3 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 4 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 5 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 6 ]
	        },{
	        	"className" : "truncate-text",
	            "targets" : [ 7 ]
	        }],
	        "createdRow": function ( row, data, index ) {
	            //控件有bug：row里的数据和显示出来的数据不一致，没有找到根源，暂时解决一下
	            setTimeout(function(){
	                for(var i=0; i<data.length; i++) {
	                    var tmpText = $('td', row).eq(i).text();
	                    $('td', row).eq(i).attr("title", tmpText);
	                }
	            }, 200);
	        }
      });
      nEditing = null;
      map = {};
}
function creatGoodsDivShow(){
    initGoodsDiv();
    $('#createSku').click();
  }

function updateGoodsDivShow(goodsid){
    initGoodsDiv();

    //后台ajax
    $.ajax({
        type:"GET",
        url:"/goods/getGoodsById.action?goodsId="+goodsid,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,//同步
        success:function(data) {
            if (data.result == "success") {
                //设置商品的信息
                $("#goodsId").val(data.goods.goodsId);
                $("#goodCode").val(data.goods.goodsCode);
                $("#goodCode").attr("title", data.goods.goodsCode);
                $("#goodName").val(data.goods.goodsName);
                $("#goodName").attr("title", data.goods.goodsName);
                $("#remark").val(data.goods.remark);
                $("#goodCodehid").val(data.goods.goodsCode);
                $("#goodNamehid").val(data.goods.goodsName);
                $("#remarkhid").val(data.goods.remark);
                $("#catgId").val(data.goods.catgId);
                $("#catgName").val(data.goods.catgName);
                $("#catgName").attr("title", data.goods.catgName);

                if(data.goods.isSn=="y"){
                    $("#isSn").iCheck("check");
                }else{
                    $("#isSn").iCheck("uncheck");
                }
                
                //设置规格信息
                $.each(data.goodsSku, function (n, value) {
                    $('#createSku').click();
                    skuCreateTable.fnUpdate(value.skuCode, n, 1, false);
                    skuCreateTable.fnUpdate(value.skuName, n, 2, false);
                    skuCreateTable.fnUpdate(value.stanPurcPrice, n, 3, false);
                    skuCreateTable.fnUpdate(value.salePrice, n, 4, false);
                    skuCreateTable.fnUpdate(value.barCode, n, 7, false);
                    if (value.giftsYn=="y"){
                        skuCreateTable.fnUpdate("是", n, 5, false);
                    } else {
                        skuCreateTable.fnUpdate("否", n, 5, false);
                    }
                    if (value.virtYn=="y"){
                        skuCreateTable.fnUpdate("是", n, 6, false);
                    } else {
                        skuCreateTable.fnUpdate("否", n, 6, false);
                    }
                    skuCreateTable.fnUpdate(value.skuMCode, n, 0, false);
                    skuCreateTable.fnUpdate('<a href="javascript:;" class="delete" goodsSkuId="'+value.skuId+'">删除</a>', n, 8, false); 
                    nEditing = null;
                    map[value.skuId] = value.skuMCode+","+value.skuCode + "," + value.skuName + "," + value.stanPurcPrice+ "," + value.salePrice  + "," + value.giftsYn + "," + value.virtYn + "," + value.barCode;
                });
                
                //设置商品分类
                
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error:function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
      
  }

